package middleware

import (
	"bytes"
	"gitee.com/baal1990/epidemic/global"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"time"
)

type BodyLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w *BodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

/*
*
请求时间记录
*/
func ReqTimeLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Start timer
		start := time.Now()
		path := c.Request.URL.Path
		method := c.Request.Method
		if method == http.MethodPost || method == http.MethodPut || method == http.MethodDelete || method == http.MethodGet {
			c.Request.ParseForm()
			global.GVA_LOG.Info(path)
		}
		// Process request
		c.Next()
		// Stop timer
		end := time.Now()
		latency := end.Sub(start)
		clientIP := c.ClientIP()
		statusCode := c.Writer.Status()
		global.GVA_LOG.Info("statusCode,latency,clientIP:", zap.Any("clientIP", clientIP))
		global.GVA_LOG.Info("statusCode,latency,latency:", zap.Any("latency", latency))
		global.GVA_LOG.Info("statusCode,latency,statusCode:", zap.Any("statusCode", statusCode))
	}
}
